Explain the file Handling in Python, with example.
Explain the file Handling in Python.
312
29-Oct-2025
Updated on 31-Oct-2025
Anubhav Kumar
31-Oct-2025Here’s a complete explanation — simple and structured
1. What Is File Handling?
Python provides a built-in function:
to interact with files.
2. Syntax of
open()Parameters:
filename→ Name or path of the file (e.g.,"data.txt"or"C:/Files/data.txt")mode→ Defines the purpose of opening the file.3. File Modes
'r''w''a''r+''w+''a+''x''b''rb','wb', etc.'t'4. Reading Files
a) Read the whole file
b) Read line by line
c) Read first N characters
5. Writing to Files
a) Overwrite existing content
b) Append to file
6. Using
withStatement (Best Practice)Using
withautomatically closes the file after use — even if an error occurs.Example:
Without
with, you’d have to close it manually:7. Checking If File Exists (Optional)
You can check file existence before opening:
8. Working with Binary Files
Example – writing and reading an image:
9. Deleting Files
10. Summary
open()open("file.txt", "r")read(),readline(),readlines()file.read()write(),writelines()file.write("text")close()file.close()os.path.exists()os.path.exists("file.txt")os.remove()os.remove("file.txt")